import os
import uuid
from typing import Any

from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from rest_framework import generics, status
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView

from movies.models import Movie
from movies.services import add_preference, add_watch_history
from movies.tasks import process_file
from movies.utils import temporary_file

from .serializers import (
    AddPreferenceSerializer,
    AddToWatchHistorySerializer,
    GeneralFileUploadSerializer,
    MovieSerializer,
)
from .services import user_preferences, user_watch_history


class MovieListCreateAPIView(generics.ListCreateAPIView):
    """电影列表和创建API视图类"""

    queryset = Movie.objects.all().order_by("id")  # 查询所有电影并按ID排序
    serializer_class = MovieSerializer  # 使用电影序列化器


class MovieDetailAPIView(generics.RetrieveUpdateDestroyAPIView):
    """电影详情API视图类"""

    queryset = Movie.objects.all()  # 查询所有电影
    serializer_class = MovieSerializer  # 使用电影序列化器


class UserPreferencesView(APIView):
    """用户偏好设置API视图类"""

    def post(self, request: Request, user_id: int) -> Response:
        """添加新的用户偏好设置"""
        serializer = AddPreferenceSerializer(data=request.data)
        if serializer.is_valid():
            add_preference(user_id, serializer.validated_data["new_preferences"])
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def get(self, request: Request, user_id: int) -> Response:
        """获取用户偏好设置"""
        data = user_preferences(user_id)
        return Response(data)


class WatchHistoryView(APIView):
    """用户观看历史API视图类"""

    def get(self, request: Request, user_id: int) -> Response:
        """获取用户观看历史"""
        data = user_watch_history(user_id)
        return Response(data)

    def post(self, request: Request, user_id: int) -> Response:
        """添加电影到用户观看历史"""
        serializer = AddToWatchHistorySerializer(data=request.data)
        if serializer.is_valid():
            add_watch_history(
                user_id,
                serializer.validated_data["id"],
            )
            return Response(
                {"message": "电影已添加到观看历史"},
                status=status.HTTP_201_CREATED,
            )
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class GeneralUploadView(APIView):
    """通用文件上传API视图类"""

    def post(self, request, *args: Any, **kwargs: Any) -> Response:
        """处理文件上传请求"""
        serializer = GeneralFileUploadSerializer(data=request.data)
        if serializer.is_valid():
            uploaded_file = serializer.validated_data["file"]
            file_type = uploaded_file.content_type

            # 提取文件扩展名
            file_extension = os.path.splitext(uploaded_file.name)[1]
            # 使用UUID生成唯一文件名
            unique_file_name = f"{uuid.uuid4()}{file_extension}"

            # 直接保存文件到默认存储
            file_name = default_storage.save(
                unique_file_name, ContentFile(uploaded_file.read())
            )
            process_file.delay(file_name, file_type)

            return Response(
                {"message": "文件处理任务已加入队列"},
                status=status.HTTP_202_ACCEPTED,
            )
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
